<!--
 * @Author: xjt
 * @Date: 2020-12-09 11:28:58
 * @LastEditTime: 2020-12-22 11:06:22
 * @Description: 合同录入弹窗组件，支持新增、编辑、查看
-->
<template>
  <div class="addDialog">
    <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" @close="handleClosed">
      <div class="dialogWrap">
        <el-form ref="dialogForm" :rules="rules" :model="formData">
          <el-col :span="24">
            <h4 class="dialogItemTitle">基本信息</h4>
          </el-col>
          <el-row :gutter="20">
            <el-col :span="6" class="listFormItem">
              <el-button class="add" size="mini" type="primary" @click="openChooseDialog('property')" v-if="type === 'add' || !hasPayMent">选择物业</el-button>
              <el-form-item label="物业名称" class="full" prop="propertyName">
                <el-input v-model="formData.propertyName" maxlength="20" readonly placeholder="请选择物业名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同编号" class="full" prop="contractNo">
                <el-input v-model="formData.contractNo" maxlength="20" :readonly="isReadonly" placeholder="请输入合同编号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同类型" class="full" prop="contractType">
                <el-select v-model="formData.contractType" placeholder="请选择合同类型" :disabled="isReadonly">
                  <el-option v-for="item in contractTypes" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="listFormItem">
              <el-button class="add" size="mini" type="primary" @click="openChooseDialog('contract')" v-if="type === 'add' || !hasPayMent">选择合同乙方</el-button>
              <el-form-item label="合同乙方" class="full" prop="unitName">
                <el-input v-model="formData.unitName" maxlength="20" readonly placeholder="请选择合同乙方" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系人" class="full" prop="contactUser">
                <el-input v-model="formData.contactUser" maxlength="20" readonly placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系电话" class="full" prop="contactTell">
                <el-input v-model="formData.contactTell" maxlength="20" readonly placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="签订日期" class="full" prop="signingDate">
                <el-date-picker v-model="formData.signingDate" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择签订日期" :readonly="isReadonly" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同金额(元)" class="full" prop="contractAmount">
                <el-input
                  v-model="formData.contractAmount"
                  maxlength="20"
                  :readonly="isReadonly || hasPayMent"
                  placeholder="请输入合同金额(元)"
                  v-only-number="{min:0, max: 999999999999999, precision:2}"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同期限" class="full" prop="daterange">
                <el-date-picker
                  v-model="formData.daterange"
                  type="daterange"
                  range-separator="-"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :readonly="isReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="付款方式" class="full" prop="paymentType">
                <el-select v-model="formData.paymentType" placeholder="请选择付款方式" :disabled="isReadonly || hasPayMent">
                  <el-option v-for="item in paymentWays" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" class="full" prop="remarks">
                <el-input v-model="formData.remarks" type="textarea" :readonly="isReadonly" :placeholder="isReadonly ? '暂无内容' : '请输入内容'" maxlength="200" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 附件 -->
          <el-row :gutter="20" class="album" v-if="dialogVisible">
            <el-col :span="24" v-if="oldFiles.length || type !== 'preview'">
              <h4 class="dialogItemTitle">上传附件</h4>
            </el-col>
            <el-col :span="24">
              <v-upload
                ref="upload"
                :busId="formData.paymentContractUnitId"
                modelType="paymentContract"
                @onSuccess="onSuccess"
                @loadCompleted="handleLoadCompleted"
                v-model="uploadFileList"
                :isView="['preview'].includes(type)"
                :canDelete="['add','edit'].includes(type)"
              />
            </el-col>
          </el-row>
        </el-form>

        <!-- 选择弹窗 -->
        <choose-dialog ref="chooseDialog" v-bind="chooseDialogAttrs" @chooseData="handleChoose" />
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button v-if="type !== 'preview'" type="primary" v-throttle="[save]">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { editContract, checkContractNo, getContractById } from "@/views/wy-operate/api/payment";
import { getDict } from '@/utils'
import { validateSocialCredit, validatePhoneTwo } from '@/utils/validate'
export default {
  name: "contractDialog",
  inject: ['initList'],
  data () {
    return {
      //弹窗类型，默认新增
      type: "add",
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        // 物业名称
        propertyName: '',
        //合同金额
        contractAmount: 0,
        // 合同期限-结束时间
        contractDeadlineEnd: "",
        // 合同期限-开始时间
        contractDeadlineStart: "",
        // 合同编号
        contractNo: "",
        // 合同类型
        contractType: "",
        // 主键
        paymentContractId: "",
        // 乙方-付款合同单位主键
        paymentContractUnitId: "",
        // 付款方式
        paymentType: "",
        // 备注
        remarks: "",
        // 物业/房源id
        roomId: "",
        // 签订日期
        signingDate: "",
        // 联系人
        contactUser: '',
        // 乙方单位名称
        unitName: '',
        // 合同有效时间
        daterange: [],
      },
      // 上传文件列表
      uploadFileList: [],
      // 已上传的文件
      oldFiles: [],
      // 校验
      rules: {
        propertyName: [{ required: true, message: "物业名称不能为空", trigger: "blur" }],
        contractNo: [
          { required: true, message: "合同编号不能为空", trigger: "blur" },
          { validator: this.handleContractNoRepeat, trigger: 'blur' },
        ],
        contractType: [{ required: true, message: "合同类型不能为空", trigger: "blur" }],
        unitName: [{ required: true, message: "合同乙方不能为空", trigger: "blur" }],
        contactUser: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
        contactTell: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          { validator: validatePhoneTwo, trigger: 'blur' },
        ],
        signingDate: [{ required: true, message: "签订日期不能为空", trigger: "blur" }],
        contractAmount: [{ required: true, message: "合同金额不能为空", trigger: "blur" }],
        daterange: [{ required: true, message: "合同期限不能为空", trigger: "blur" }],
        paymentType: [{ required: true, message: "付款方式不能为空", trigger: "blur" }],
      },
      // 选择弹窗属性数据
      chooseDialogAttrs: {}
    };
  },
  computed: {
    // 弹窗标题计算
    dialogTitle () {
      return {
        preview: "查看",
        edit: "编辑",
        add: "新增"
      }[this.type];
    },
    // 判断是否只读
    isReadonly () {
      return ["preview"].includes(this.type);
    },
    // 编辑的时候如果存在付款记录 那么合同金额、乙方、物业、付款方式将不能修改
    hasPayMent () {
      return this.formData.isPayRecord == 1
    },
    // 合同类型
    contractTypes () {
      return getDict('payment-contract-type')
    },
    // 付款方式
    paymentWays () {
      return getDict('payment-contract-pay-way')
    }
  },
  methods: {
    //开启弹窗
    show ({ type, data = {} }) {
      if (['preview', 'edit'].includes(type)) {
        this.formData.paymentContractId = data.paymentContractId;
        getContractById(data.paymentContractId).then(res => {
          let info = res.data.data
          let daterange = info.contractDeadlineStart && info.contractDeadlineStart ? [info.contractDeadlineStart, info.contractDeadlineEnd] : []
          this.formData = { ...this.formData, ...info, daterange };
        })
      }
      this.type = type;
      this.dialogVisible = true;
    },
    // 提交新增
    save () {
      if (['edit', 'add'].includes(this.type)) {
        this.$refs.dialogForm.validate(validate => {
          validate && this.$refs.upload.submit();
        })
      }
    },
    // 上传成功
    async onSuccess (response, file, fileList) {
      let params = this.type == 'add' ? { ...this.formData, paymentContractId: response.data } : JSON.parse(JSON.stringify(this.formData))
      if (params.daterange.length) {
        params.contractDeadlineStart = params.daterange[0]
        params.contractDeadlineEnd = params.daterange[1]
      }
      const res = await editContract(params, this.type)
      if (res.data.code == 0) {
        this.$message.success(`${this.dialogTitle}成功!`);
        this.initList({ keyword: '', current: 1 })
        this.dialogVisible = false;
      } else {
        this.$message.error(res.data.msg)
      }
    },
    // 弹窗关闭还原
    handleClosed () {
      this.uploadFileList.length = 0
      for (var i in this.formData) {
        this.formData[i] = Object.prototype.toString.call(this.formData[i]) == '[object Array]' ? [] : ''
      }
      this.$refs.dialogForm.resetFields();
    },
    // 监听上传组件上传完成
    handleLoadCompleted (data) {
      this.oldFiles = data
    },
    // 开启选择弹窗
    openChooseDialog (type) {
      this.chooseDialogAttrs = {
        property: {
          title: '选择物业',
          placeholder: '请输入物业名称',
          url: '/api/payment/contract/search/property',
          primaryKey: 'roomId',
          width: "1000px",
          showData: [
            { prop: 'propertyName', label: '物业名称', width: '200', align: 'center' },
            { prop: 'propertyAddress', label: '物业地址' },
          ]
        },
        contract: {
          title: '选择合同乙方单位',
          placeholder: '请输入单位名称',
          url: '/api/payment/contract/unit/page',
          primaryKey: 'paymentContractUnitId',
          width: "1200px",
          showData: [
            { prop: 'unitName', label: '单位名称', width: '200', align: 'center' },
            { prop: 'address', label: '地址', align: 'center' },
            { prop: 'contactUser', label: '联系人', width: '140', align: 'center' },
            { prop: 'contactTell', label: '联系电话', width: '200', align: 'center' },
            { prop: 'contactPhone', label: '联系人手机', width: '200', align: 'center' },
          ],
          returnData: ['paymentContractUnitId', 'contactPhone', 'contactTell', 'unitName', 'contactUser'],
        }
      }[type]
      this.$nextTick(() => {
        this.$refs.chooseDialog.show()
      })
    },
    // 监听弹窗选中
    handleChoose (data) {
      this.formData = { ...this.formData, ...data }
    },
    // 校验合同编号是否重复
    handleContractNoRepeat (rule, value, callback) {
      let params = { contractNo: value }
      if (this.type === 'edit') {
        params.paymentContractId = this.formData.paymentContractId
      }
      checkContractNo(params, this.type).then(res => {
        if (res.data.code == 0 && res.data.data) {
          return callback()
        }
        return callback(new Error('合同编号不能重复'))
      })
    }
  },
};
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.addDialog {
  /deep/ .el-dialog__body {
    padding: 10px 20px;
  }
}
</style>
